<template>
  <div class="settings-container">
    <div class="settings-header">
      <button class="back-button" v-if="settings.showBackButton" @click="goBack">
        <span class="back-icon">←</span> 返回
      </button>
      <h1 class="settings-title">系统设置</h1>
    </div>

    <div class="settings-tabs" v-kbd-trap.roving="settings.enableKeyboardNavigation">
      <button 
        v-for="tab in tabs" 
        :key="tab.id"
        class="tab-button"
        :class="{ active: activeTab === tab.id }"
        @click="activeTab = tab.id"
      >
        {{ tab.name }}
      </button>
    </div>

    <div class="settings-content">
      <div v-show="activeTab === 'database'" class="tab-content">
        <div class="settings-section" v-kbd-trap.roving="settings.enableKeyboardNavigation">
          <h2 class="section-title">数据库设置</h2>
        
        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">远程数据库更新</span>
            <span class="setting-description">从远程服务器更新题库数据</span>
          </div>
          <div class="setting-control">
            <button 
              class="update-button" 
              :class="{ 'loading': isUpdating }" 
              @click="updateDatabase" 
              :disabled="isUpdating"
            >
              {{ isUpdating ? '更新中...' : '立即更新' }}
            </button>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">自动更新</span>
            <span class="setting-description">启动时自动检查并更新题库</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.autoUpdate">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">更新服务器地址</span>
            <span class="setting-description">设置数据库更新的服务器地址</span>
          </div>
          <div class="setting-control">
            <input 
              type="text" 
              v-model="settings.serverUrl" 
              placeholder="https://example.com/api"
              class="text-input"
            >
          </div>
        </div>
        </div>
      </div>

      <div v-show="activeTab === 'game'" class="tab-content">
        <div class="settings-section" v-kbd-trap.roving="settings.enableKeyboardNavigation">
          <h2 class="section-title">游戏设置</h2>
        
        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">倒计时功能</span>
            <span class="setting-description">在游戏中启用倒计时限制</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.enableCountdown">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item" v-show="settings.enableCountdown">
          <div class="setting-label">
            <span class="setting-name">倒计时时长</span>
            <span class="setting-description">设置每题的答题时间（秒）</span>
          </div>
          <div class="setting-control">
            <button 
              class="duration-button" 
              @click="openDurationModal"
            >
              {{ settings.countdownDuration }} 秒
            </button>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">音效</span>
            <span class="setting-description">启用游戏音效</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.enableSound">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">背景音乐</span>
            <span class="setting-description">启用游戏背景音乐</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.enableMusic">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>
        </div>
      </div>

      <div v-show="activeTab === 'controls'" class="tab-content">
        <div class="settings-section" v-kbd-trap.roving="settings.enableKeyboardNavigation">
          <h2 class="section-title">按键设置</h2>
        
        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">显示返回按钮</span>
            <span class="setting-description">在游戏界面显示返回按钮</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.showBackButton">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">ESC键返回</span>
            <span class="setting-description">使用ESC键快速返回上一级</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.enableEscapeKey">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">右键菜单退出</span>
            <span class="setting-description">右键点击显示退出确认菜单</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.enableContextMenu">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>

        <div class="setting-item">
          <div class="setting-label">
            <span class="setting-name">键盘导航</span>
            <span class="setting-description">启用方向键和回车键导航</span>
          </div>
          <div class="setting-control">
            <label class="toggle">
              <input type="checkbox" v-model="settings.enableKeyboardNavigation">
              <span class="toggle-slider"></span>
            </label>
          </div>
        </div>
        </div>
      </div>

      <div v-show="activeTab === 'questions'" class="tab-content">
        <div class="settings-section" v-kbd-trap.roving="settings.enableKeyboardNavigation">
          <h2 class="section-title">题库管理</h2>
        
          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">重置所有题目</span>
              <span class="setting-description">将所有题目标记为未使用状态</span>
            </div>
            <div class="setting-control">
              <button 
                class="danger-button" 
                @click="resetAllRiddles"
              >
                重置
              </button>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">题库统计</span>
              <span class="setting-description">查看当前题库数量统计</span>
            </div>
            <div class="setting-control">
              <button 
                class="info-button" 
                @click="showDatabaseStats"
              >
                查看统计
              </button>
            </div>
          </div>
        </div>
      </div>

      <div v-show="activeTab === 'network'" class="tab-content">
        <div class="settings-section" v-kbd-trap.roving="settings.enableKeyboardNavigation">
          <h2 class="section-title">网络状态</h2>
          
          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">HTTP服务</span>
              <span class="setting-description">游戏HTTP服务器状态</span>
            </div>
            <div class="setting-control">
              <span :class="['status-indicator', networkStatus.httpActive ? 'active' : 'inactive']">
                {{ networkStatus.httpActive ? '运行中' : '已停止' }}
              </span>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">WebSocket服务</span>
              <span class="setting-description">游戏WebSocket服务器状态</span>
            </div>
            <div class="setting-control">
              <span :class="['status-indicator', networkStatus.websocketActive ? 'active' : 'inactive']">
                {{ networkStatus.websocketActive ? '运行中' : '已停止' }}
              </span>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">本地IP地址</span>
              <span class="setting-description">当前设备网络地址</span>
            </div>
            <div class="setting-control">
              <span class="ip-address">{{ networkStatus.localIp }}</span>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">刷新IP地址</span>
              <span class="setting-description">重新获取本地IP地址</span>
            </div>
            <div class="setting-control">
              <button 
                class="refresh-button" 
                @click="refreshNetworkInfo"
                :disabled="isRefreshingIP"
              >
                {{ isRefreshingIP ? '刷新中...' : '立即刷新' }}
              </button>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-label">
              <span class="setting-name">清除IP缓存</span>
              <span class="setting-description">清除已缓存的IP地址信息</span>
            </div>
            <div class="setting-control">
              <button 
                class="danger-button" 
                @click="clearNetworkCache"
              >
                清除缓存
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>



    <!-- 弹窗组件 -->
    <div class="modal" v-if="showModal">
      <div class="modal-content" v-kbd-trap.escexits>
        <div class="modal-header">
          <h2>{{ modalTitle }}</h2>
          <button class="close-button" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <p v-if="modalType === 'success'" class="success-message">{{ modalMessage }}</p>
          <p v-else-if="modalType === 'error'" class="error-message">{{ modalMessage }}</p>
          <p v-else>{{ modalMessage }}</p>

          <div v-if="modalType === 'stats'" class="stats-container">
            <div class="stat-item" v-for="(count, game) in databaseStats" :key="game">
              <span class="stat-name">{{ getGameName(game) }}</span>
              <span class="stat-value">{{ count }} 题</span>
            </div>
          </div>

          <div v-if="modalType === 'duration'" class="duration-input-container">
            <input 
              ref="durationInput"
              type="number" 
              v-model.number="tempDuration" 
              min="5" 
              max="120"
              class="duration-input"
              @keydown.enter="confirmDuration"
              @keydown.escape="closeModal"
            >
            <span class="duration-unit">秒</span>
          </div>
        </div>
        <div class="modal-footer">
          <button v-if="modalType === 'duration'" class="primary-button" @click="confirmDuration">确定</button>
          <button v-if="modalType === 'duration'" class="secondary-button" @click="closeModal">取消</button>
          <button v-if="modalType !== 'duration'" class="primary-button" @click="closeModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { getSetting, updateSetting } from '../utils/settings';
import { VueKeyboardTrapDirectiveFactory } from '@pdanpdan/vue-keyboard-trap';
import { getKeySettings, setupGlobalKeyHandlers, type KeySettings } from '../utils/keySettings';
import { getNetworkInfo, refreshIP, clearIPCache } from '../utils/ipManager';

// 配置键盘陷阱指令
const vKbdTrap = VueKeyboardTrapDirectiveFactory({
  // 启用键盘导航功能
  // 支持ESC键退出焦点陷阱
  // 支持roving tabindex模式进行方向键导航
}).directive;

const router = useRouter();
const tabs = [
  { id: 'database', name: '数据库' },
  { id: 'game', name: '游戏设置' },
  { id: 'controls', name: '按键设置' },
  { id: 'questions', name: '题库管理' },
  { id: 'network', name: '网络设置' }
];
const activeTab = ref('database');

// 网络状态
const networkStatus = reactive({
  httpActive: false,
  websocketActive: false,
  localIp: '获取中...'
});

// 设置状态
const settings = reactive({
  autoUpdate: false,
  serverUrl: 'https://tv-games-api.example.com',
  enableCountdown: true,
  countdownDuration: 30,
  enableSound: true,
  enableMusic: true,
  showBackButton: false,
  enableEscapeKey: true,
  enableContextMenu: true,
  enableKeyboardNavigation: true
});

// 按键设置
const keySettings = reactive<KeySettings>({
  showBackButton: true,
  enableEscapeKey: true,
  enableContextMenu: true,
  enableKeyboardNavigation: true
});

// 更新状态
const isUpdating = ref(false);
const isRefreshingIP = ref(false);

// 弹窗状态
const showModal = ref(false);
const modalTitle = ref('');
const modalMessage = ref('');
const modalType = ref('');
const databaseStats = ref<Record<string, number>>({});

// 倒计时时长输入相关
const tempDuration = ref(30);
const durationInput = ref<HTMLInputElement>();

// 返回上一页
const goBack = () => {
  router.push('/');
};



// 更新数据库
const updateDatabase = async () => {
  isUpdating.value = true;
  
  try {
    // 这里应该调用 Tauri 命令更新数据库
    // 例如: await invoke('update_database', { url: settings.serverUrl });
    
    // 模拟更新过程
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    showSuccessModal('更新成功', '数据库已成功更新到最新版本。');
  } catch (error) {
    showErrorModal('更新失败', '更新数据库时发生错误，请检查网络连接或服务器地址。');
    console.error('更新数据库失败:', error);
  } finally {
    isUpdating.value = false;
  }
};

// 重置所有谜语
const resetAllRiddles = async () => {
  try {
    // 调用 Tauri 命令重置所有谜语
    // await invoke('reset_riddles');
    
    showSuccessModal('重置成功', '所有题目已重置为未使用状态。');
  } catch (error) {
    showErrorModal('重置失败', '重置题目时发生错误，请稍后重试。');
    console.error('重置谜语失败:', error);
  }
};

// 显示数据库统计
const showDatabaseStats = async () => {
  try {
    // 这里应该调用 Tauri 命令获取数据库统计
    // const stats = await invoke('get_database_stats');
    
    // 模拟数据
    databaseStats.value = {
      'riddle_game': 50,
      'brain_teaser_game': 30,
      'idiom_game': 40
    };
    
    showStatsModal('题库统计', '当前题库数量统计：');
  } catch (error) {
    showErrorModal('获取失败', '获取题库统计信息失败，请稍后重试。');
    console.error('获取数据库统计失败:', error);
  }
};

// 获取游戏名称
const getGameName = (gameId: string): string => {
  const gameNames: Record<string, string> = {
    'riddle_game': '猜谜语',
    'brain_teaser_game': '脑筋急转弯',
    'idiom_game': '成语接龙'
  };
  
  return gameNames[gameId] || gameId;
};

// 显示成功弹窗
const showSuccessModal = (title: string, message: string) => {
  modalTitle.value = title;
  modalMessage.value = message;
  modalType.value = 'success';
  showModal.value = true;
};

// 显示错误弹窗
const showErrorModal = (title: string, message: string) => {
  modalTitle.value = title;
  modalMessage.value = message;
  modalType.value = 'error';
  showModal.value = true;
};

// 显示统计弹窗
const showStatsModal = (title: string, message: string) => {
  modalTitle.value = title;
  modalMessage.value = message;
  modalType.value = 'stats';
  showModal.value = true;
};

// 关闭弹窗
const closeModal = () => {
  showModal.value = false;
};

// 打开倒计时时长设置弹窗
const openDurationModal = () => {
  tempDuration.value = settings.countdownDuration;
  modalTitle.value = '设置倒计时时长';
  modalMessage.value = '请输入每题的答题时间（5-120秒）';
  modalType.value = 'duration';
  showModal.value = true;
  
  // 延迟聚焦到输入框
  setTimeout(() => {
    durationInput.value?.focus();
    durationInput.value?.select();
  }, 100);
};

// 确认倒计时时长设置
const confirmDuration = () => {
  if (tempDuration.value >= 5 && tempDuration.value <= 120) {
    settings.countdownDuration = tempDuration.value;
    closeModal();
  } else {
    showErrorModal('输入错误', '倒计时时长必须在5-120秒之间');
  }
};

// 加载设置
const loadSettings = async () => {
  try {
    settings.autoUpdate = (await getSetting('auto_update')) === 'true';
    settings.serverUrl = (await getSetting('server_url')) || 'https://tv-games-api.example.com';
    settings.enableCountdown = (await getSetting('enable_countdown')) === 'true';
    settings.countdownDuration = parseInt((await getSetting('countdown_duration')) || '30');
    settings.enableSound = (await getSetting('enable_sound')) === 'true';
    settings.enableMusic = (await getSetting('enable_music')) === 'true';
    settings.showBackButton = (await getSetting('show_back_button')) === 'true'; // 明确检查是否为'true'
    settings.enableEscapeKey = (await getSetting('enable_escape_key')) !== 'false'; // 默认为true
    settings.enableContextMenu = (await getSetting('enable_context_menu')) !== 'false'; // 默认为true
    settings.enableKeyboardNavigation = (await getSetting('enable_keyboard_navigation')) !== 'false'; // 默认为true
  } catch (error) {
    console.error('加载设置失败:', error);
  }
};

// 监听所有设置项变化，实现实时保存
watch(() => settings.autoUpdate, async (newValue) => {
  await updateSetting('auto_update', newValue.toString());
});

watch(() => settings.serverUrl, async (newValue) => {
  await updateSetting('server_url', newValue);
});

watch(() => settings.enableCountdown, async (newValue) => {
  await updateSetting('enable_countdown', newValue.toString());
});

watch(() => settings.countdownDuration, async (newValue) => {
  await updateSetting('countdown_duration', newValue.toString());
});

watch(() => settings.enableSound, async (newValue) => {
  await updateSetting('enable_sound', newValue.toString());
});

watch(() => settings.enableMusic, async (newValue) => {
  await updateSetting('enable_music', newValue.toString());
});

watch(() => settings.showBackButton, async (newValue) => {
  await updateSetting('show_back_button', newValue.toString());
});

watch(() => settings.enableEscapeKey, async (newValue) => {
  await updateSetting('enable_escape_key', newValue.toString());
});

watch(() => settings.enableContextMenu, async (newValue) => {
  await updateSetting('enable_context_menu', newValue.toString());
});

watch(() => settings.enableKeyboardNavigation, async (newValue) => {
  await updateSetting('enable_keyboard_navigation', newValue.toString());
});

// 加载按键设置的函数
const loadKeySettings = async () => {
  const keySettingsData = await getKeySettings();
  Object.assign(keySettings, keySettingsData);
};

// 页面获得焦点时重新加载设置
const handleVisibilityChange = () => {
  if (!document.hidden) {
    loadKeySettings();
  }
};

// 组件挂载时加载设置
// 获取本地IP地址（使用新的IP管理器）
const loadNetworkStatus = async () => {
  try {
    const networkInfo = await getNetworkInfo();
    networkStatus.localIp = networkInfo.localIp;
    networkStatus.httpActive = networkInfo.httpActive;
    networkStatus.websocketActive = networkInfo.websocketActive;
  } catch (error) {
    networkStatus.localIp = '获取失败';
    networkStatus.httpActive = false;
    networkStatus.websocketActive = false;
    console.error('获取网络状态失败:', error);
  }
};

// 刷新网络信息
const refreshNetworkInfo = async () => {
  isRefreshingIP.value = true;
  
  try {
    // 强制刷新IP地址
    const newIP = await refreshIP();
    
    // 重新加载网络状态
    await loadNetworkStatus();
    
    showSuccessModal('刷新成功', `IP地址已更新为: ${newIP}`);
  } catch (error) {
    showErrorModal('刷新失败', '刷新IP地址时发生错误，请稍后重试。');
    console.error('刷新网络信息失败:', error);
  } finally {
    isRefreshingIP.value = false;
  }
};

// 清除网络缓存
const clearNetworkCache = async () => {
  try {
    await clearIPCache();
    
    // 重新加载网络状态
    networkStatus.localIp = '获取中...';
    await loadNetworkStatus();
    
    showSuccessModal('清除成功', 'IP缓存已清除，已重新获取网络信息。');
  } catch (error) {
    showErrorModal('清除失败', '清除IP缓存时发生错误，请稍后重试。');
    console.error('清除网络缓存失败:', error);
  }
};

onMounted(async () => {
  // 获取网络状态
  await loadNetworkStatus();
  // 加载设置数据
  await loadSettings();
  
  // 初始加载按键设置
  await loadKeySettings();
  
  // 设置全局按键处理器
  const cleanup = setupGlobalKeyHandlers(keySettings, {
    onEscape: () => goBack(),
    onContextMenu: (e: MouseEvent) => {
      e.preventDefault();
      goBack();
    }
  });
  
  // 监听页面可见性变化，当页面重新获得焦点时重新加载设置
  document.addEventListener('visibilitychange', handleVisibilityChange);
  
  // 组件卸载时清理
  onUnmounted(() => {
    cleanup();
    document.removeEventListener('visibilitychange', handleVisibilityChange);
  });
});

// 组件卸载时的清理工作
onUnmounted(() => {
  // 清理工作（如果需要）
});

/**
 * 键盘导航功能现在由vue-keyboard-trap库处理
 * 该库提供了更稳定和可访问的焦点管理功能
 * 支持roving tabindex模式，自动处理方向键导航
 * 无需手动管理焦点状态和事件监听
 */
</script>

<style lang="scss" scoped>
@use './Settings.scss';
</style>
